package com.example.testProject.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.example.testProject.domain.po.user.User;
import com.example.testProject.domain.qo.user.AddQo;
import com.example.testProject.domain.qo.user.ListQo;
import com.example.testProject.domain.vo.user.ListVo;
import com.example.testProject.mapper.UserMapper;
import com.example.testProject.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * TODO
 *
 * @author czx
 * @date 2022/9/23 17:41
 */
@Service
@RequiredArgsConstructor
public class UserServiceImpl implements UserService {

    private final UserMapper userMapper;

    @Override
    @Transactional(readOnly = true)
    public ListVo doList(ListQo listQo) {
        LambdaQueryWrapper<User> qwForUser = Wrappers.<User>lambdaQuery().eq(listQo.getId() != null, User::getId, listQo.getId());
        List<User> userList = userMapper.selectList(qwForUser);

        List<ListVo.Meta> userMateList = userList.stream()
                .map(this::userForListMate)
                .collect(Collectors.toList());
        return new ListVo().setUserList(userMateList);
    }

    /**
     * @param user user
     * @return ListVo.Meta
     */
    private ListVo.Meta userForListMate(User user) {
        ListVo.Meta meta = new ListVo.Meta();
        BeanUtils.copyProperties(user, meta);
        return meta;
    }

    @Override
    public int doAdd(AddQo addQo) {
        User user = new User();
        BeanUtils.copyProperties(addQo, user);
        int row = userMapper.insert(user);
        return row;
    }
}
